#include "database/dbwrapper.h"
#include "dataroot.h"

#include "datamidi.h"
#include "dataroot.h"
#include "datalocator.h"




DBWrapper::DBWrapper()
{    
    dbase_ = new Db(new DataRoot(), ROOT, 0);
    root()->data->setRecId(root());
//    for (int i = 0; i< DBWrapper::N_LOCATORS; ++i){
//        add(new DataLocator(i), 0);
//    }
}


void DBWrapper::remove(const AData & data)
{
    if (data.recId()==NULL) return;
    dbase_->deleteRecord(static_cast<Db::RecId>(data.recId()));
}

void DBWrapper::move(const AData & data, gl::TicksTime time)
{
    if (data.recId()==NULL) return;
    dbase_->moveRecord(static_cast<Db::RecId>(data.recId()), time);
}

void DBWrapper::add(DataMidi * data, gl::TicksTime time)
{ add_specialized(data, time, root()->data, MIDI); }

void DBWrapper::add(DataLocator * data, gl::TicksTime time)
{ add_specialized(data, time, root()->data, LOCATOR); }

void DBWrapper::add_specialized
(AData * data, gl::TicksTime time, const AData * parent, Type type)
{
    if (parent->recId()==NULL || data->recId()!=NULL) return;
    data->setRecId( dbase_->addRecord(
                        data,type,time,(Db::RecId)parent->recId()));
}

DBWrapper::Rec * DBWrapper::locator(int id){
    foreach(Rec * r, *root()->children){
        if (r->type == DBWrapper::LOCATOR)
            if (static_cast<DataLocator *>(r->data)->id() == id) return r;
    }
    return NULL;
}

void DBWrapper::dump(Rec * r) const{
    gl::log(QString("DB: record : type %1 ; time %2").arg(r->type).arg(r->index));
}
